package com.ruoyi.web.controller.backstage;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysShortUrl;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysShortUrlService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Administrator
 */
@RequestMapping("/")
@RestController
public class ShortUrlController extends BaseController {

    @Resource
    private ISysShortUrlService iSysShortUrlService;

    @Resource
    private TokenService tokenService;

    @RequestMapping("link/{shortUrl}")
    @ResponseBody
    public void shortUrl(@PathVariable("shortUrl") String shortUrl, HttpServletResponse response, HttpServletRequest request) {
        SysShortUrl sysShortUrl = iSysShortUrlService.selectSysShortUrlByShotUrl(shortUrl);
        if (sysShortUrl != null && sysShortUrl.getShortUrl() != null) {
            try {
                response.sendRedirect(sysShortUrl.getSrcUrl());
                logger.info("跳转短链接：{}  成功", shortUrl);
            } catch (IOException e) {
                logger.info("跳转短链接：{}  失败原因为：{}", shortUrl, e.getMessage());
                e.printStackTrace();
            } finally {
                int i = iSysShortUrlService.deleteSysShortUrlByShotUrl(shortUrl);
                String message = i > 0 ? "跳转短链接完成,删除短链接成功" : "跳转短链接完成,删除短链接失败";
                logger.info("{} ：短链为：{},当前时间：{}", message, shortUrl, DateUtils.systemDate());
            }
        } else {
            logger.info("未知URL:{}", shortUrl);
        }
    }
    @RequestMapping("getShortUrl/hasShortUrl")
    @ResponseBody
    public AjaxResult userNo( HttpServletResponse response, HttpServletRequest request) {
        boolean aBool =false;
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String userNo = loginUser.getUser().getUserNo();
        int i = iSysShortUrlService.selectSysShortUrlCountByUserNo(userNo);
        if (i > 0) {
            aBool=true;
            int j = iSysShortUrlService.deleteSysShortUrlByUserNo(userNo);
            String message = j > 0 ? "查询是否有短连接完成,删除短链接成功" : "查询是否有短连接完成,删除短链接失败";
            logger.info("{} ,登陆人为：{} , 当前时间：{}", message, userNo,DateUtils.systemDate());
        }
        return AjaxResult.success(aBool);
    }
}
